package yl.hs.bmipfull.controllers.home;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.pojo.vehiclemanage.TruckInfoEntity;
import yl.hs.bmipfull.security.SecurityUtils;
import yl.hs.bmipfull.service.flow.IFlowUserTaskService;
import yl.hs.bmipfull.service.laboratory.IPackageInfoService;
import yl.hs.bmipfull.service.laboratory.IProductCateService;
import yl.hs.bmipfull.service.material.IRawMaterialCateService;
import yl.hs.bmipfull.service.production.IProductionLineService;
import yl.hs.bmipfull.service.system.*;
import yl.hs.bmipfull.service.vehiclemanage.ITruckInfoService;
import yl.hs.bmipfull.utils.CK;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.MachineUtils;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActiveDeviceType;
import yl.hs.bmipfull.viewmodels.WebResult;
import yl.hs.bmipfull.viewmodels.system.ActiveStateModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HomeController
 * @category
 * @author 谢景广
 * @date 2021-05-14
 */
@Api(value = "首页系统信息加载", tags = "网站首页——系统信息")
@RequestMapping("/api/home")
@RestController
public class HomeController extends ControllerBase {
    @Value("${active.day}")
    private Integer activeDays;

    @ApiOperation(value = "系统主要信息", notes = "系统菜单、数据字典、系统设置、当前用户信息")
    @RequestMapping(value = "/{type}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult mainData(@PathVariable Integer type) {
        try {
            if(type==null){
                type = 0;
            }
            var user = HsApp.getCurrent();
            if (user == null) {
                var userName = SecurityUtils.getUsername();
                var userEntity = userSvc.findUserByAccount(userName);
                var company = organizeSvc.findBySn(userEntity.getCompanySN());
                user = HsApp.addCurrent(userEntity,company.getFullName());
            }
            if (user != null) {
                var dataMap = new HashMap<String, Object>();
                var userInfo = userSvc.findUserBySN(user.getUserSN());
                dataMap.put("user_info", userInfo);

                var appSets = setSvc.querySetObjByUnitSn(userInfo.getCompanySN().split(","));
                var menuData = roleSvc.findUserMenus(userInfo.getSn(), user.getAccount().equals(appSets.get(CK.SupperAdminKey)));
                ActiveDeviceType deviceType = ActiveDeviceType.getType(type);
                // 激活天数
                ActiveStateModel activeStateModel = new ActiveStateModel(100,null);
                var day = activeService.getAvailableDays(deviceType);
                if(ObjectUtil.isNotEmpty(activeDays)){
                    day = activeStateModel;
                }
                var carinfo = truckInfoService.queryBydriverSN(userInfo.getSn());
                //day=10;
                dataMap.put("menu_list",day.getDays()>=0? menuData:new ArrayList<>());
                dataMap.put("searchCodes", searchItemSvc.queryItemsByCodes(getUserSearchRang(menuData)));
                dataMap.put("roles",roleSvc.getAllRoleMap());
                dataMap.put("duty",dutySvc.getAllDutyMap());
                dataMap.put("packages",packageSvc.getAllPackage());
                dataMap.put("proLines",proLineSvc.getAllLines());
                dataMap.put("organize",organizeSvc.getAllOrgMap());
                dataMap.put("productCate",productCateService.getAllCateMap());
                dataMap.put("rmCate",rmCateSvc.getAllCateMap());
                appSets.remove("supperAdministrator");
                dataMap.put("sys_settings", appSets);
                dataMap.put("available_days",day);
                dataMap.put("MachineID", MachineUtils.makeMachineCode(deviceType));
                dataMap.put("data_items", dictSvc.queryObjDataAll());
                var org =organizeSvc.findRootUnit();
                dataMap.put("corpID",org.getSn());
                dataMap.put("corpName",org.getFullName());
                dataMap.put("data_items", dictSvc.queryObjDataAll());
                if(carinfo!=null){
                    dataMap.put("carinfo",carinfo);
                }else{
                    dataMap.put("carinfo",new TruckInfoEntity());
                }
                try {
                    dataMap.put("area_tree", Tl.areaToOptionTreeList(areaService.queryList()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return success("ok", dataMap);
            } else {
                return new WebResult(401);
            }
        }
        catch (Exception ee){
            return  error(ee);
        }
    }

    private List<String> getUserSearchRang(List<Map<String,Object>> menuList){
        List<String> codeList = new ArrayList<>();
        for (var item : menuList){
            if(item.get("dataCode")!=null){
                var codeString = item.get("dataCode").toString();
                if(Tl.isEmpty(codeString)==false){
                    codeList.add(codeString);
                }
            }
            if(item.get("children")!=null){
                List<Map<String,Object>> child = (List<Map<String,Object>>)item.get("children");
                if(child.size()>0){
                    codeList.addAll(getUserSearchRang(child));
                }
            }
        }
        return  codeList;
    }

    @ApiOperation(value = "系统主要信息", notes = "系统菜单、数据字典、系统设置、当前用户信息")
    @PutMapping(value = "/heartbeat")
    @ResponseBody
    public WebResult heartbeat(){
        return success("ok");
    }

    @ApiOperation(value = "系统主要信息", notes = "系统菜单、数据字典、系统设置、当前用户信息")
    @RequestMapping(value = "{userSN}", method = RequestMethod.PATCH)
    @ResponseBody
    public WebResult userData(@PathVariable String userSN) {
        var dataMap = new HashMap<String, Integer>();
        // dataMap.put("inform_status", flowTaskSvc.queryUnProcessMessageCount(userSN));
        dataMap.put("task_status", msgSvc.queryUnReadMessageCount(userSN));
        return success("ok", dataMap);
    }


    @ApiOperation(value = "离线激活", notes = "系统激活")
    @RequestMapping(value = "/offLineActive", method = RequestMethod.POST)
    @ResponseBody
    public WebResult offLineActive(@RequestBody Map<String,String> model){
        try {
            var result = activeService.active(model.get("activeCode"), ActiveDeviceType.ERPPC);
            if(result>0) {
                return success("激活成功", true);
            }
            else
            {
                return fail("激活失败");
            }
        }
        catch (Exception ee){
            return error(ee);
        }
    }

    @ApiOperation(value = "在线激活", notes = "系统激活")
    @RequestMapping(value = "/onLineActive", method = RequestMethod.GET)
    @ResponseBody
    public WebResult onLineActive(){
        try {
            var result = activeService.onlineActive();
             activeService.onlineDealerActive();
             activeService.onlineERPMobileActive();
             activeService.onlineSupplierActive();
             activeService.onlineConstructionActive();
             activeService.onlineDriverActive();
            if(result>0) {
                return success("激活成功", true);
            }
            else
            {
                return fail("激活失败");
            }
        }
        catch (Exception ee){
            return error(ee);
        }
    }



    @Autowired
    IFlowUserTaskService flowTaskSvc;
    @Autowired
    ITruckInfoService  truckInfoService;
    @Autowired
    IDataDictService dictSvc;

    @Autowired
    IRoleService roleSvc;
    @Autowired
    IUserService userSvc;

    @Autowired
    IActiveService activeService;

    @Autowired
    IAppSettingService setSvc;

    @Autowired
    ISiteMessageReceiptService msgSvc;

    @Autowired
    IAreaService areaService;

    @Autowired
    IDutyInfoService dutySvc;

    @Autowired
    IGlobalSearchService searchItemSvc;

    @Autowired
    IOrganizationInfoService organizeSvc;

    @Autowired
    IProductCateService productCateService;

    @Autowired
    IRawMaterialCateService rmCateSvc;

    @Autowired
    IPackageInfoService packageSvc;

    @Autowired
    IProductionLineService proLineSvc;
}
